<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <el-form :rules="rules" :model="ruleform" ref="ruleForm" label-width="80px">
      <el-form-item label="登录名称" prop="username" >
        <el-input v-model="ruleform.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="ruleform.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="ruleform.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交修改</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: "UserInfo",
  data() {
    return {
      // 收集表单数据对象
      ruleform: { ...this.$store.state.userInfo }, //
      // 验证规则对象
      rules: {
        nickname: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
          {
            pattenr: /^\S{1,10}$/,
            message: "请输入1~10位的非空字符串",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur"],
          },
        ],
      },
    };
  },
  methods: {
    // 修改用户信息
    submit() {
      // 1. 绑定事件函数
      // 2. 兜底校验
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return; // 校验失败
        // 发送axios请求
        const { data: res } = await this.$http.put(
          "/my/userinfo",
          this.ruleform
        );
        // 输入
        if (!res.code === 0) return this.$message.error(res.message);
        // 4. 重新获取用户信息, 重新渲染
        this.$store.dispatch("initUserInfo");
      });
    },
    // 重置数据
    resetForm() {
      this.ruleform = { ...this.$store.state.userInfo };
    },
  },
};
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
